import Taro from '@tarojs/taro'
import request from '../utils/request'
import type { 
  LoginParams, 
  LoginResponse, 
  User 
} from '../types/api'

class AuthService {
  async login(params: LoginParams): Promise<LoginResponse> {
    const response = await request.post<LoginResponse>('/auth/login', params)
    
    if (response.code === 0) {
      this.setUserToken(response.data.token)
      this.setUserInfo(response.data.user)
    }
    
    return response.data
  }

  async logout(): Promise<void> {
    await request.post('/auth/logout')
    this.clearUserData()
  }

  async getUserInfo(): Promise<User> {
    const response = await request.get<User>('/auth/user')
    return response.data
  }

  async updateUserProfile(userData: Partial<User>): Promise<User> {
    const response = await request.put<User>('/auth/user', userData)
    
    if (response.code === 0) {
      this.setUserInfo(response.data)
    }
    
    return response.data
  }

  setUserToken(token: string): void {
    request.setToken(token)
    Taro.setStorageSync('token', token)
  }

  getUserToken(): string | null {
    return Taro.getStorageSync('token') || null
  }

  setUserInfo(user: User): void {
    Taro.setStorageSync('userInfo', user)
  }

  getUserInfoFromStorage(): User | null {
    return Taro.getStorageSync('userInfo') || null
  }

  clearUserData(): void {
    request.removeToken()
    Taro.removeStorageSync('token')
    Taro.removeStorageSync('userInfo')
  }

  isLoggedIn(): boolean {
    return !!this.getUserToken()
  }
}

export const authService = new AuthService()
export default authService